package org.company.tool.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.junit.runners.model.InitializationError;

/**
 * Velocity模板类相关函数
 * @author hucw
 *
 */
public class VelocityUtil {
	
	private static VelocityUtil instance;
	
	private VelocityUtil() {
		Properties prop = new Properties();
		try {
			prop.load(VelocityUtil.class.getResourceAsStream("/velocity.properties"));
			Velocity.init(prop);
		} catch (Exception e) {
			new InitializationError(e).printStackTrace();
		}
	}
	
	/**
	 * 获取VelocityContext对象
	 * @return
	 */
	public VelocityContext createContext() {
		return new VelocityContext();
	}
	
	/**
	 * 读取vmUri模板文件，生成targetUri文件
	 * @param vmUri vm文件路径
	 * @param targetUri 生成文件路径
	 * @param context VelocityContext
	 * @throws IOException 
	 */
	public void mergeTemplate(String vmUri,String targetUri,VelocityContext context) {
		BufferedWriter writer = null;
	    File file = new File(targetUri);
	    if(!file.exists()) {
	        new File(file.getParent()).mkdirs();
	    }
        try {
            writer = new BufferedWriter(new FileWriter(targetUri));
        } catch (IOException e) {
            e.printStackTrace();
        }
		this.mergeTemplate(vmUri, context, writer);
	}
	
	public void mergeTemplate(String vmUri,VelocityContext context,Writer writer) {
	    Template template = null;
	    try {
            template = Velocity.getTemplate(vmUri);
            template.merge(context, writer);
            writer.flush();
        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
        } catch (ParseErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	public static VelocityUtil getInstance() {
		if(instance == null) {
			instance = new VelocityUtil();
		}
		return instance;
	}
}
